package com.tool.weixin.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;

import org.slf4j.Logger;

public class HttpUtils {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(HttpUtils.class);


	 /**
     * 发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("Weixin server connection timed out.");
        } catch (Exception e) {
            logger.error("https request error:{}", e);
        }
        return jsonObject;
    }
    /**
     * 下载文件
     * @param requestUrl 请求地址
     * @param filepath 文件保存路径
     * @param type 文件类型
     */
    public static JSONObject downFile(String requestUrl,String filepath,String type) {
    	JSONObject jsonObject = null;
    	File file = new File(filepath);
    	if(!file.exists()) {
    		file.mkdirs();
    	}
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("GET");

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            String contentType = httpUrlConn.getHeaderField("Content-Type");
            
            if(contentType.equals("text/plain")) {
            	BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream,
            			"UTF-8")); 
	        	String str = null;
	        	StringBuffer buffer = new StringBuffer();
	            while ((str = rd.readLine()) != null) {
	                buffer.append(str);
	            }
	            jsonObject = JSONObject.fromObject(buffer.toString()); 
            	rd.close();
            } else {
            	BufferedInputStream bis = new BufferedInputStream(inputStream);
                
                String disposition = httpUrlConn.getHeaderField("content-disposition");
                //微信服务器生成的文件名称
                String[] content_arr = disposition.split(";");
                String tmp = content_arr[1];
                int index = tmp.indexOf("\"");
                String fileName =tmp.substring(index+1, tmp.length()-1);
                
    			byte[] buf = new byte[1024];
    			File temp = new File(filepath+fileName);
    			OutputStream fileOut = new FileOutputStream(temp);
    			int size = 0;
    			while ((size = bis.read(buf)) != -1) {
    				fileOut.write(buf, 0, size);  
    			}
    			fileOut.flush();
    			fileOut.close();
    			jsonObject = JSONObject.fromObject("{filepath:'"+filepath+"',filename:'"+fileName+"'}");
            }
            
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
        } catch (ConnectException ce) {
        	ce.printStackTrace();
            logger.error("Weixin server connection timed out.");
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("https request error:{}", e);
        }
        return jsonObject;
    }
    /**
     * 上传文件
     * @param requestUrl 请求地址
     * @param filepath 文件路径
     * @return
     */
    public static JSONObject uploadFile(String requestUrl, String filepath) {
    	File file = new File(filepath);
    	InputStream inputStream = null;
    	try {
    		inputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
    	return uploadFile(requestUrl,file.getName(), inputStream);
    }
    /**
     * 上传文件
     * @param requestUrl 请求地址
     * @param filename 文件名
     * @param fileInputStream 文件流
     * @return
     */
    public static JSONObject uploadFile(String requestUrl,String filename, InputStream fileInputStream) {
    	
        String boundary = "----------" + System.currentTimeMillis();
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("POST");
            // 设置请求内容类型
            httpUrlConn.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
            
            // 当有数据需要提交时
	        StringBuilder sb = new StringBuilder();
	        sb.append("--"); // ////////必须多两道线

	        sb.append(boundary);
	        sb.append("\r\n");
	        sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
	                + filename + "\"\r\n");
	        sb.append("Content-Type:application/octet-stream\r\n\r\n");
	        byte[] head = sb.toString().getBytes("utf-8");
	        // 获得输出流
	        OutputStream out = new DataOutputStream(httpUrlConn.getOutputStream());
	        out.write(head);
	        
	        // 文件正文部分
	        DataInputStream in = new DataInputStream(fileInputStream);
	        int bytes = 0;
	        byte[] bufferOut = new byte[1024];
	        while ((bytes = in.read(bufferOut)) != -1) {
	            out.write(bufferOut, 0, bytes);
	        }
	        in.close();
	        // 结尾部分

	        byte[] foot = ("\r\n--" + boundary + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线

	        out.write(foot);
	        out.flush();
	        out.close();
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("Weixin server connection timed out.");
        } catch (Exception e) {
            logger.error("https request error:{}", e);
        }
        return jsonObject;
    }
}
